<template>
  <view :style="{width: width}">
    <u-upload :file-list="fileList" multiple :capture="capture" :upload-icon="uploadIcon" :max-count="maxCount" @afterRead="afterRead" @delete="deletePic" />
  </view>
</template>

<script>
export default {
  name: 'UploadImage',
  props: {
    modelValue: {
      type: String,
      default: undefined
    },
    dir: {
      type: String,
      default: undefined
    },
    width: {
      type: String,
      default: '100%'
    },
    uploadIcon: {
      type: String,
      default: 'camera-fill'
    },
    capture: {
      type: [String, Array],
      default: () => {
        ['album', 'camera']
      }
    },
    maxCount: {
      type: Number,
      required: false,
      default: 3
    },
    afterUpload: {
      type: Object,
      required: false,
      default: undefined
    }

  },
  data() {
    return {
      fileList: [],
      imgUrlList: []
    }
  },
  watch: {
    modelValue: {
      immediate: true,
      handler(val) {
        this.fileList = []
        if (this.isNull(val)) {
          return
        }
        try {
          this.fileList = JSON.parse(val)
        } catch {
          val.split(',').forEach(item => {
            this.fileList.push({
              url: item
            })
          })
        }
      }
    }
  },
  methods: {
    // 删除图片
    deletePic(event) {
      this.fileList.splice(this.fileList.indexOf(event.file), 1)
      this.emit()
    },
    // 新增图片
    afterRead(event) {
      const lists = [].concat(event.file)
      lists.forEach(item => {
        this.uploadFilePromise(item)
      })
    },
    // 上传图片
    uploadFilePromise(item) {
      let url = process.env.config[process.env.NODE_ENV].VITE_APP_BASE_API + '/json/oss/upload'
      if (!this.isNull(this.dir)) {
        url = url + `?dir=${this.dir}`
      }
      uni.uploadFile({
        url: url,
        filePath: item.url,
        name: 'file',
        success: (response) => {
          const res = JSON.parse(response.data)
          if (res.success) {
            const file = { name: item.name, url: res.data }
            this.fileList.push(file)
            this.emit()
          } else {
            this.$u.toast(`${item.name}上传失败`)
          }
        }
      })
    },
    emit() {
      this.$emit('update:modelValue', JSON.stringify(this.fileList))
    }
  }
}
</script>
